<template>
  <div v-loading="leftTreeLoading" class="vxetable-tree-container">
    <el-button-group style="min-width: 209px; margin-bottom: 10px">
      <el-button :icon="Refresh" type="primary" @click="handleRefresh"> 刷新 </el-button>
      <el-button :icon="Expand" type="primary" @click="expandAll()"> 展开 </el-button>
      <el-button :icon="Fold" type="primary" @click="collapseAll()"> 收起 </el-button>
      <el-button v-if="isShow" type="primary" @click="showDisabled"> 显示停用 </el-button>
    </el-button-group>
    <el-input v-model="filterText" placeholder="输入关键字进行过滤" style="width: 100%" />
    <div class="down-tree" :style="{ height: treeHeightRef }">
      <vxe-table
        ref="xTable"
        :data="tableData"
        :radio-config="{
          labelField: 'nodename',
          visibleMethod: ({ row }) => false
        }"
        :row-config="{
          keyField: 'id',
          useKey: 'id',
          isCurrent: true, //当鼠标点击行时，是否要高亮当前行
          isHover: true //当鼠标移到行时，是否要高亮当前行
        }"
        :show-header="false"
        show-overflow="true"
        :tree-config="{
          showLine: true,
          iconOpen: 'vxe-icon-square-minus',
          iconClose: 'vxe-icon-square-plus',
          transform: true,
          rowField: 'id',
          parentField: 'parentid',
          expandRowKeys: expandRowKeys
        }"
        @cell-click="handleCellClick"
        @cell-dblclick="handleCellDbClick"
      >
        <vxe-column tree-node type="radio" />
      </vxe-table>
    </div>
  </div>
</template>

<script setup>
import { Refresh, Expand, Fold } from "@element-plus/icons-vue";
import { queryList } from "@/api/mains";

const leftTreeLoading = ref(false);

const props = defineProps({
  treeHeight: {
    type: String,
    default: ""
  },
  treeRootId: {
    type: String,
    default: "0"
  },
  url: {
    type: String,
    default: ""
  },
  queryForm: {
    type: Object,
    default: () => {
      return {};
    }
  }
});

const emit = defineEmits(["treeNodeClick", "get-expand-row-keys"]);

const filterText = ref();

const queryFormRef = ref(props.queryForm);
const allData = ref([]);
const tableData = ref([]);
const isShow = ref(false);
const selectRow = ref(); //当前选中的行
const expandRowKeys = ref([]); //默认展开的行

const xTable = ref();
const treeHeightRef = ref("");

const handleCellClick = ({ row }) => {
  //在点击文字的时候并不会高亮，需要自行设置高亮
  xTable.value.clearCurrentRow();
  xTable.value.setCurrentRow(row);
  selectRow.value = row;
  emit("treeNodeClick", row.id);
};

const handleCellDbClick = ({ row }) => {
  const expandRecords = xTable.value.getTreeExpandRecords();
  let hasExpand = false;
  expandRecords.forEach(record => {
    if (record.id == row.id) {
      hasExpand = true;
      return;
    }
  });
  //xTable.value.isExpandByRow(row)
  if (hasExpand) {
    xTable.value.setTreeExpand(row, false);
  } else {
    xTable.value.setTreeExpand(row, true);
  }
};

const showDisabled = () => {
  console.info("showDisabled>>>>");
};

const handleRefresh = async () => {
  leftTreeLoading.value = true;
  treeHeightRef.value = props.treeHeight;
  const responseData = await queryList(props.url, { ...queryFormRef.value, pageSize: -1 });
  tableData.value = responseData.data.rows;
  allData.value = responseData.data.rows;
  // expandRowKeys.value.push(props.treeRootId);//只会在初始化时被触发一次

  setTimeout(function () {
    responseData.data.rows.forEach((item, index) => {
      let expandArr = [];
      if (item.parentid == props.treeRootId) {
        expandArr.push(xTable.value.getData(index));
      }
      xTable.value.setTreeExpand(expandArr, true);
    });
  }, 10); // 定时时间

  // responseData.data.rows.forEach(item => {
  //   if (item.parentid == props.treeRootId) {
  //     expandRowKeys.value.push(item.id);
  //   }
  // });
  leftTreeLoading.value = false;
  emit("get-expand-row-keys", expandRowKeys);
};

//展开树
const expandAll = () => {
  xTable.value.setAllTreeExpand(true);
};
//折叠树
const collapseAll = () => {
  xTable.value.setAllTreeExpand(false);
};

onBeforeMount(() => {
  handleRefresh();
});

watch(
  () => filterText.value,
  val => {
    if (val == null || val.trim() == "") {
      tableData.value = allData.value;
    } else {
      const filterdatas = [];
      allData.value.forEach(item => {
        if (item.nodename.indexOf(val) >= 0) {
          filterdatas.push(item);
        }
      });
      tableData.value = filterdatas;
    }
  }
);

defineExpose({ handleRefresh });
</script>
<style lang="scss" scoped>
.el-button-group {
  display: flex;
  .el-button {
    flex: auto;
  }
  .el-button {
    padding: 5px 3px;
  }
}
.down-tree {
  width: 100%;
  margin-top: 10px;
  overflow: auto;
  :deep(.vxe-body--column) {
    padding: 3px 0;
  }
}
:deep(.vxe-table--body) {
  .vxe-body--column {
    background-image: none;
  }
}
:deep(.vxe-table) {
  .vxe-table--border-line {
    border: none;
  }
}
:deep() {
  .vxe-table--render-default .vxe-body--column.col--ellipsis {
    height: 34px;
  }
}

$base: ".vxetable-tree";
#{$base}-container {
  position: relative;
  padding: 0 !important;

  /* background: $base-color-background !important; */
  :deep() {
    .vxe-tree--btn-wrapper {
      i {
        color: #1890ff;
      }
    }
    .vxe-tree-cell {
      font-size: 12px;
    }
    .posirow {
      position: absolute;
      inset: 0;
      .el-col {
        height: 100%;
      }
    }
    .el-card {
      height: 100%;
      margin-bottom: 0 !important;
      .el-card__body {
        height: 100%;
        padding: 10px;
      }
    }
    .el-select-dropdown__item {
      padding: 0;
    }
    .el-select-dropdown {
      height: 300px !important;
    }
    .el-scrollbar .el-scrollbar__view .el-select-dropdown__item {
      height: auto;
      max-height: 274px;
      padding: 0;
      overflow: hidden;
      overflow-y: auto;
    }
    .el-select-dropdown__item {
      overflow: initial !important;
    }
    .el-form-item--small.el-form-item {
      margin-bottom: 10px;
    }
    .el-button--mini {
      padding: 7px 5%;
    }
    .el-input,
    .el-select--small {
      width: 34%;
    }
    .el-select .el-input {
      width: 100% !important;
    }
    .el-icon-caret-right::before {
      display: none;
    }
    .demo-form label {
      font-size: 14px;
      color: #999999;
    }
    .filter-tree {
      margin-top: 10px;
    }
    .el-button-group {
      width: 100%;
    }
  }
}
</style>
